//
//  FANativeAutoTrack.swift
//  flutter_auto_track
//
//  Created by leonard on 2024/6/5.
//

import Foundation
import RangersAppLog
import BDASignalSDK

public class FANativeAutoTrack: NSObject {
    
    static var BDDID: String?
    static var queryBDDIDFinished = false
    static var queryBDDIDCallback: ((String)->())?
    static var queryBDIDOverTimer: Timer?
    
    static let shared = FANativeAutoTrack()
    
    /// 初始化归因sdk
    static func setupWith(value: Any?) {
        guard let configValue = value as? [String: Any] else { return }
        guard let jsonData = try? JSONSerialization.data(withJSONObject: configValue,
                                                         options: .fragmentsAllowed),
              let config = FATrackConfigs.toObject(with: jsonData)
        else { return }
        NotificationCenter.default.removeObserver(self)
        queryBDDIDFinished = false
        queryBDIDOverTimer?.invalidate()
        queryBDIDOverTimer = nil
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(onRegisterSuccess),
                                               name: NSNotification.Name(rawValue: BDAutoTrackNotificationRegisterSuccess),
                                               object: nil)
        let trackConfig = BDAutoTrackConfig(appID: config.appid,
                                            launchOptions: FlutterAutoTrackPlugin.launchOptions)
        trackConfig.channel = config.channel
        trackConfig.enableDeferredALink = true
        trackConfig.autoTrackEnabled = config.enabledAutoTrack
        trackConfig.logNeedEncrypt = config.needEncrypt
        trackConfig.showDebugLog = config.openDebugMode
        BDAutoTrack.sharedTrack(with: trackConfig)
        BDAutoTrack.start()
        BDAutoTrack.setALinkRoutingDelegate(FANativeAutoTrack.shared)
        BDAutoTrack.setCustomHeaderValue("1", forKey: "csj_attribution")
        /// 广告转化融合归因
        BDASignalManager.register(withOptionalData: [:])
        BDASignalManager.didFinishLaunching(options: FlutterAutoTrackPlugin.launchOptions,
                                            connect: nil)
        BDASignalManager.enableIdfa(true)
        BDASignalManager.enableDelayUpload()
        BDASignalManager.startSendingEvents()
    }
    
    /// 自定义上报
    static func eventWith(arguments: Any?) {
        guard let trackArguments = arguments as? [String: Any] else { return }
        var eventName = ""
        var eventParams = [String: Any]()
        if let name = trackArguments["name"] as? String {
            eventName = name
        }
        if let params = trackArguments["params"] as? [String: Any] {
            eventParams = params
        }
        BDAutoTrack.eventV3(eventName, params: eventParams)
        BDASignalManager.trackEssentialEvent(withName: eventName,
                                             params: eventParams)
    }
    
    /// 获取AdSpark必要数据
    static func queryDeviceBDDIDValue(arguments: Any?, callback: @escaping ((String)->())) {
        queryBDIDOverTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: false, block: { timer in
            timer.invalidate()
            if !queryBDDIDFinished {
                queryBDDIDFinished = true
                callback("")
            }
        })
        let noValue = BDDID?.isEmpty ?? true
        if !noValue {
            queryBDDIDFinished = true
            callback(BDDID ?? "")
        } else {
            queryBDDIDCallback = callback
        }
    }
    
    /// 广告归因转化处理打开APP的deeplink
    public static func handlerOpenApp(with url: URL) {
        BDASignalManager.anylyseDeeplinkClickid(withOpenUrl: url.absoluteString)
    }
    
    /// 获取广告归因的clickId
    public static func queryClickId() -> String? {
        return BDASignalManager.getClickId()
    }
    
    /// 监听设备唯一id
    @objc static func onRegisterSuccess(noti: Notification) {
        guard let value = noti.userInfo else {
            let noValue = BDDID?.isEmpty ?? true
            if !noValue && !queryBDDIDFinished {
                queryBDDIDFinished = true
                queryBDDIDCallback?(BDDID ?? "")
            }
            return
        }
        BDDID = value[kBDAutoTrackNotificationRangersDeviceID] as? String
        if !queryBDDIDFinished {
            queryBDDIDFinished = true
            queryBDDIDCallback?(BDDID ?? "")
        }
    }
}

extension FANativeAutoTrack: BDAutoTrackAlinkRouting {
    public func onAttributionData(_ routingInfo: [AnyHashable : Any]?, error: (any Error)?) {
        
    }
    
    public func onALinkData(_ routingInfo: [AnyHashable : Any]?, error: (any Error)?) {
        
    }
    
    public func shouldALinkSDKAccessPasteBoard() -> Bool {
        return true
    }
}
